package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.service.IWechatService;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 * @author Lorine
 * @date 2025/3/3 17:05
 */
@Service
public class WechatServiceImpl implements IWechatService {

    private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session";
    private static final String PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";
    @Value("${wechat.appid}")
    private String appid;

    @Value("${wechat.secret}")
    private String secret;

    @Override
    public String getOpenId(String code) {
        HashMap<String, Object> params = getConfig();
        params.put("js_code", code);
        params.put("grant_type", "authorization_code");
        String result = HttpUtil.get(REQUEST_URL, params);
        JSONObject obj = JSONUtil.parseObj(result);
        if (ObjectUtil.isNotNull(obj.getInt("errcode"))) {
            throw new RuntimeException(obj.getStr("errmsg"));
        }
        return obj.getStr("openid");
    }

    private HashMap<String, Object> getConfig() {
        HashMap<String, Object> params = new HashMap<>();
        params.put("appid", appid);
        params.put("secret", secret);
        return params;
    }

    @Override
    public String getToken() {
        HashMap<String, Object> params = getConfig();
        params.put("grant_type", "client_credential");
        String result = HttpUtil.get(TOKEN_URL, params);
        JSONObject obj = JSONUtil.parseObj(result);
        if (ObjectUtil.isNotNull(obj.getInt("errcode"))) {
            throw new RuntimeException(obj.getStr("errmsg"));
        }
        return obj.getStr("access_token");
    }

    @Override
    public String getPhone(String phoneCode) {
        HashMap<String, Object> params = new HashMap<>();
        params.put("code", phoneCode);
        String token = getToken();
        HttpResponse response = HttpUtil.createPost(PHONE_URL + token).body(JSONUtil.toJsonStr(params)).execute();
        if (response.isOk()) {
            JSONObject obj = JSONUtil.parseObj(response.body());
            if (obj.getInt("errcode") != 0) {
                throw new RuntimeException(obj.getStr("errmsg"));
            }
            return obj.getJSONObject("phone_info").getStr("phoneNumber");
        } else {
            throw new BaseException("获取失败");
        }
    }
}
